package cn.com.huzo.webapp.controller.purchase;

import cn.com.huzo.model.entities.purchase.NotesPayabledHeaderEntity;
import cn.com.huzo.model.entities.purchase.NotesPayabledLinesPoStockInEntity;
import cn.com.huzo.service.purchase.NotesPayabledHeaderManager;
import cn.com.huzo.service.purchase.NotesPayabledLinesManager;
import huzofw.common.web.controller.BaseFormController;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.PathVariable;
import cn.com.huzo.service.purchase.NotesPayabledLinesPoStockInManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.MapUtils;

/**
 * 对账单画面控制器
 *
 * @author 吴旭
 */
@Controller
@RequestMapping(value = "/purchase/notes_payabled")
public class NotesPayabledController extends BaseFormController {

    // <editor-fold defaultstate="collapsed" desc="属性">
    @Resource(name = "NotesPayabledHeaderManager")
    private NotesPayabledHeaderManager _manager_header;

    @Resource(name = "NotesPayabledLinesPoStockInManager")
    private NotesPayabledLinesPoStockInManager _manager_lines_po_stockin;

    @Resource(name = "NotesPayabledLinesManager")
    private NotesPayabledLinesManager _manager_lines;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="画面处理部分">
    /**
     * 跳转到对账单一览画面
     * <p>
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/list.html")
    public ModelAndView redirectListWnd(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("purchase.notes_payabled.list.def");
        return view;
    }

    /**
     * 跳转对账单编辑画面
     * <p>
     * @param request 上下文请求
     * @param action 操作类别 1：增加 2：编辑
     * @param headerId 主表ID
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/{action}/{headerId}/edit.html")
    public ModelAndView redirectEditWnd(HttpServletRequest request, @PathVariable(value = "action") int action,
            @PathVariable(value = "headerId") Long headerId) throws Exception {
        ModelAndView view = new ModelAndView();
        // 为画面设置变量
        view.addObject("action", action);
        view.addObject("headerId", headerId);
        int thisYear = Calendar.getInstance().get(Calendar.YEAR); // 得到今年
        List<Integer> yearList = new ArrayList();
        thisYear = thisYear - 5;
        for (int i = 0; i < 11; i++) {
            yearList.add(thisYear);
            thisYear = thisYear + 1;
        }
        view.addObject("YearList", yearList);             // 设置对账年份选择列表数据
        view.setViewName("purchase.notes_payabled.edit.def");

        return view;
    }

    /**
     * 应付款订单到货选择画面
     * <p>
     * @return
     */
    @RequestMapping("/account_payable/choice.html")
    public ModelAndView redirectAccountPayableChoiceWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.purchase.account_payable.choice.def");
        return view;
    }

    /**
     * 批量更新税率、发票号、开票日等信息
     * <p>
     * @return
     */
    @RequestMapping("/lines/sync.html")
    public ModelAndView redirectPieceYardageLinesProductColourPopupWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.purchase.notes_payabled_lines.sync.def");
        return view;
    }

    /**
     * 对账单打印预览画面
     * <p>
     * @return
     */
    @RequestMapping("/header/print.html")
    public ModelAndView redirectPrintPreviewWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("print.purchase.notes_payabled.print.def");
        return view;
    }

    /**
     * 对账单导出设置画面
     * <p>
     * @return
     */
    @RequestMapping("/export/setting.html")
    public ModelAndView redirectExportSettingWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.purchase.notes_payabled_export.setting.def");
        return view;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="主表-数据处理部分">
    /**
     * 得到新的单据号
     * <p>
     * @return @throws Exception
     */
    @RequestMapping(value = "/header/fetchNewBillNo.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchNewBillNo() throws Exception {
        Map<String, Object> _result = new HashMap();
        _result.put("BillNo", _manager_header.fetchNewBillNo());
        return _result;
    }

    /**
     * 根据标识取得对账单数据。
     *
     * @param criterion 对账单标识
     * @return 对账单数据（包括主表和子表）。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/header/fetchByKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchByKey(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.fetchByHeaderKey(criterion);
    }

    /**
     * 根据条件取得对账单信息分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 对账单信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/header/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchForPage(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.fetchForPage(criterion);
    }

    /**
     * 新增、保存对账单信息数据
     *
     * @param instance 要处理的对账单信息对象
     * @return 新增记录主键或更新影响的行数
     * @throws Exception
     */
    @RequestMapping(value = "/header/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Long save(@RequestBody final NotesPayabledHeaderEntity instance) throws Exception {
        Long rowsAffected;

        if (instance.getHeaderId() > 0) { // 编辑
            rowsAffected = (long) _manager_header.update(instance);
        } else {                          // 新增
            rowsAffected = _manager_header.insert(instance);
        }

        return rowsAffected;
    }

    /**
     * 删除对账单信息数据。
     *
     * @param criterion 对账单标识
     * @return 影响的行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/header/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> delete(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.delete(criterion);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="明细-到货情况数据处理部分">
    /**
     * 根据条件取得对账单明细信息分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 对账单明细信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/lines/postockin/fetch.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<NotesPayabledLinesPoStockInEntity> fetchPoStockInLines(@RequestBody Map<String, Object> criterion) throws Exception {
        return _manager_lines_po_stockin.fetchByHeaderKey(criterion);
    }

    /**
     * 增加到货情况信息数据。
     *
     * @param criterion 对账单标识
     * @return 到货情况列表和对账明细表。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/postockin/add.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> addPoStockInLines(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_po_stockin.add(criterion);
    }

    /**
     * 删除对账单-明细（到货情况）信息数据。
     *
     * @param criterion 对账单标识
     * @return 到货情况列表和对账明细表。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/postockin/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deletePoStockInLines(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_po_stockin.delete(criterion);
    }

    /**
     * 批量删除对账单-明细（到货情况）信息数据。
     *
     * @param criterion 要删除的数据
     * @return 到货情况列表和对账明细表。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/postockin/batchDelete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> batchDeleteLinesStockIn(@RequestBody final Map<String, Object> criterion) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        List<NotesPayabledLinesPoStockInEntity> _deletedLinesList = mapper.convertValue(MapUtils.getObject(criterion, "DeletedLinesList"), new TypeReference<List<NotesPayabledLinesPoStockInEntity>>() {
        });

        if (_deletedLinesList.isEmpty()) {
            Map<String, Object> _result = new HashMap();
            _result.put("Success", false);
            return _result;
        } else {
            return _manager_lines_po_stockin.batchDeleteLines(
                    MapUtils.getLong(criterion, "HeaderId"),
                    MapUtils.getLong(criterion, "DeletedBy"),
                    MapUtils.getInteger(criterion, "Limit02"),
                    MapUtils.getString(criterion, "OrderBy"),
                    _deletedLinesList);
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="明细-数据处理部分">
    /**
     * 根据条件取得对账单明细信息分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 对账单明细信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/lines/fetchLinesForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchLinesForPage(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines.fetchForPage(criterion);
    }

    /**
     * 更新明细信息数据。
     *
     * @param criterion 对账单标识
     * @return 影响行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/update.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateLines(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines.batchUpdate(criterion);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="到货对账数据处理部分">
    /**
     * 得到到货对账数据数据。
     *
     * @param criterion 要搜索的条件
     * @return 向导中的列表明细数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/account_payable/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchAccountPayableForPage(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_po_stockin.fetchAccountPayableForPage(criterion);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="打印预览及导出处理部分">
    /**
     * 得到打印预览画面数据
     *
     * @param criterion 条件：对账单标识、接单公司标识
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fetchPrintPreviewData.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchExportDataWithStyleNoByHeaderId(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_header.fetchExportDataWithStyleNoByHeaderId(MapUtils.getLong(criterion, "HeaderId"), null);
    }

    /**
     * 导出excel
     *
     * @param request 上下文请求
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export.html",
            method = RequestMethod.POST)
    public ModelAndView exportViewExceNotesPayabled(HttpServletRequest request) throws Exception {
        Long headerId = Long.parseLong(request.getParameter("_Export_HeaderId").trim());
        Integer styleNoFlag = Integer.parseInt(request.getParameter("_Export_StyleNoFlag").trim());

        Map<String, Object> model = _manager_header.fetchExportDataWithStyleNoByHeaderId(headerId, styleNoFlag);

        return new ModelAndView("NotesPayabledExcelView", model);
    }
    // </editor-fold>
}
